﻿using System;
using System.Linq;
using Wolfpack.Periscope.Core.Interfaces.Entities;
using Wolfpack.Periscope.Core.Interfaces.Events;

namespace Wolfpack.Periscope.Core
{    
    public partial class Dashboard
    {
        private void HandleAddPanelToDashboardEvent(AddPanelToDashboardCommand args)
        {
            var config = _repository.Load();
            var existingPanel = config.Panels.FirstOrDefault(x => x.Name.Equals(args.Content.Name, 
                StringComparison.OrdinalIgnoreCase));

            if (existingPanel != null)
                throw new InvalidOperationException(string.Format("Dashboard already contains a panel named '{0}'!",
                    args.Content.Name));

            var sequence = config.Panels.Max(x => x.Sequence) + 1;

            var instance = new DashboardPanelConfiguration
            {
                Name = args.Content.Name,
                DwellInSeconds = args.Content.DwellInSeconds,
                Sequence = sequence
            };

            config.AddPanel(instance);

            _repository.Save(config);

            _infrastructure.MessageBus.Publish(new PanelAddedEvent(this, new PanelReference
            {
                PanelId = instance.Id,
                PanelName = instance.Name,
                PanelVersion = instance.Version
            }));
        }
    }
}